<? if (!defined('DB_PEREFIX')) exit;

global $db, $SITE, $GLOBAL_USER;


if (!isset($GLOBAL_USER)) die('0');
if (!isset($_POST['blog_id']) || !isset($_POST['type'])) die('1');

$id = intval($_POST['blog_id']);
$get_com = $db->query ("SELECT cat_users FROM ".DB_PEREFIX."_art_category WHERE cat_id = '$id'");
if ($db->num_rows($get_com) != 1) die('2');

$com = $db->fetch_array ($get_com);

$user_com = $GLOBAL_USER['user_blogs'];


if ($_POST['type'] == 'join') 
{
	if ($user_com == '') 
		$new = $id;
	else 
		$new = "$user_com,$id";

	$db->query ("UPDATE ".DB_PEREFIX."_users SET user_blogs = '$new' WHERE user_id = '{$GLOBAL_USER['user_id']}'");
	$db->query ("UPDATE ".DB_PEREFIX."_art_category SET cat_users = '".($com['cat_users']+1)."' WHERE cat_id = '$id'");
	
	$opt = "";
	$file = file_get_contents ($_SERVER['DOCUMENT_ROOT']."/modules/system/views/elements.tpl");
	preg_match ("#{exit_blog}(.+?){/exit_blog}#is", $file, $element);
	$opt .= str_replace ("{ID}", $id, $element[1]);
	print $opt;
}
elseif (in_blog ($id)) 
{
	$comm = explode (",", $user_com);
	if (count($comm) == 1) $new = "";
	else 
	{
		if ($comm[0] == $id) 
			$new = substr ($user_com, strlen($com[0]), strlen($user_com)-1);
		else 
		{
			$new_ = explode (",$id", $user_com);
			$new = $new_[0].$new[1];
		}
	}
	$db->query ("UPDATE ".DB_PEREFIX."_users SET user_blogs = '$new' WHERE user_id = '{$GLOBAL_USER['user_id']}'");
	$db->query ("UPDATE ".DB_PEREFIX."_art_category SET cat_users = '".(intval($com['cat_users'])-1)."' WHERE cat_id = '$id'");
	
	$opt = "";
	$file = file_get_contents ($_SERVER['DOCUMENT_ROOT']."/modules/system/views/elements.tpl");
	preg_match ("#{join_blog}(.+?){/join_blog}#is", $file, $element);
	$opt .= str_replace ("{ID}", $id, $element[1]);
	print $opt;
	
}
else die('5');

function in_blog ($id) 
{
	global $GLOBAL_USER;
	$com = explode (",", $GLOBAL_USER['user_blogs']);
	foreach ($com as $c) if ($c == $id) return true;
	return false;
}

exit;
?>
